package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.BaiduMapUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.webSocketServer.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private BaiduMapUtil baiduMapUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //判断购物车非空
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.isEmpty())
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        //判断地址非空
        AddressBook addressBook = addressBookMapper.selectById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null)
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
//        送单范围是否超出
        String address = addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail();
        if (baiduMapUtil.main(address) > 5000){
            throw new OrderBusinessException("超出配送范围");
        }

        //构建订单信息
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
//        插入订单信息
        orderMapper.insert(orders);
//        构建订单明细
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList){
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
//        将订单明细插入订单明细表
        orderDetailMapper.insertBatch(orderDetailList);
//        清空购物车以便进行下次下单操作
        shoppingCartMapper.cleanSC(BaseContext.getCurrentId());
//        封装订单明细信息以返回前端
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();

        return orderSubmitVO;
    }

    /**
     * 历史订单查询
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult pageResult(int page,int pageSize,Integer status) {
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        PageHelper.startPage(page,pageSize);
        Page<Orders> ordersPage=orderMapper.pageQuery(ordersPageQueryDTO);

//        查询订单明细
        List<OrderVO> orderVOList = new ArrayList<>();
        if (ordersPage != null && ordersPage.getTotal() > 0) {
            for (Orders orders : ordersPage) {
                List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetailList);
                orderVOList.add(orderVO);
            }
        }
        long total = ordersPage.getTotal();
        return new PageResult(total,orderVOList);
    }

    /**
     * 用户取消订单
     * @param id
     */
    @Override
    public void cancel(Long id) {
//        判断订单是否存在
        Orders orders = orderMapper.selectById(id);
        if (orders == null)
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
//        判断订单状态是否可取消
        if (orders.getStatus() > 2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
//        1.订单退款
//        1.1新建订单对象以备状态安全更新
        Orders orderUpdata = new Orders();
        orderUpdata.setId(orders.getId());

//        1.2订单处于待接单状态时，将支付状态改为退款
        if (orders.getStatus() == 2){
            // TODO: 2024/2/28 支付功能待完善
            orders.setStatus(Orders.REFUND);
        }

//        1.3取消订单
        orderUpdata.setStatus(Orders.CANCELLED);
        orderUpdata.setCancelReason("用户取消");
        orderUpdata.setCancelTime(LocalDateTime.now());
        orderMapper.upDate(orderUpdata);
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO selectById(Long id) {
        Orders orders = orderMapper.selectById(id);
        List<OrderDetail> orderDetail = orderDetailMapper.getByOrderId(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetail);
        return orderVO;
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void payMore(Long id) {
        List<OrderDetail> orders = orderDetailMapper.getByOrderId(id);
        List<ShoppingCart> shoppingCartList = new ArrayList<>();
        for (OrderDetail o : orders) {
            ShoppingCart sc = new ShoppingCart();
            BeanUtils.copyProperties(o, sc);
            sc.setUserId(BaseContext.getCurrentId());
            sc.setCreateTime(LocalDateTime.now());
            shoppingCartList.add(sc);
        }
        // TODO: 2024/2/28 可以尝试把功能改成往购物车添加商品，而不是覆盖购物车已有的商品
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.selectById(id);
        if (orders == null)
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);

        Map map = new HashMap();
        map.put("type",2);
        map.put("orderId",orders.getId());
        map.put("content","订单号"+orders.getNumber());

        String json = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    /**
     * 订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> orderVOList = new ArrayList<>();
        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)){
            for (Orders orders : ordersList){
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders,orderVO);
//                获取菜品名
                Long ordersId = orders.getId();
                List<OrderDetail> byOrderId = orderDetailMapper.getByOrderId(ordersId);
                for (OrderDetail orderDetail : byOrderId){
                    String orderDish = orderDetail.getName() +"*"+ orderDetail.getNumber();
                    orderVO.setOrderDishes(orderDish);
                }
                orderVOList.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(),orderVOList);
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statusCount() {
        Integer toBeConfirmed = orderMapper.statusCound(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.statusCound(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.statusCound(Orders.DELIVERY_IN_PROGRESS);

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * 商家取消订单
     * @param ordersCancelDto
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDto) throws Exception {
        // TODO: 2024/2/29 退款处理？
        Orders orders = orderMapper.selectById(ordersCancelDto.getId());
        if (orders.getPayStatus() == Orders.PAID){
            String refund = weChatPayUtil.refund(
                    orders.getNumber(),
                    orders.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01)
            );
        }

        Long ordersId = ordersCancelDto.getId();
        String cancelReason = ordersCancelDto.getCancelReason();
        Orders ordersUpdate = new Orders();
        ordersUpdate.setId(ordersId);
        ordersUpdate.setStatus(Orders.CANCELLED);
        ordersUpdate.setCancelReason(cancelReason);
        ordersUpdate.setCancelTime(LocalDateTime.now());
        orderMapper.upDate(ordersUpdate);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders orders = orderMapper.selectById(id);
        if (orders == null && !Objects.equals(orders.getStatus(), Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders ordersUpdate = new Orders();
        ordersUpdate.setId(orders.getId());
        ordersUpdate.setStatus(Orders.COMPLETED);
        ordersUpdate.setDeliveryTime(LocalDateTime.now());
        orderMapper.upDate(ordersUpdate);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void deliver(Long id) {
        Orders orders = orderMapper.selectById(id);
        if (orders == null && !Objects.equals(orders.getStatus(), Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders ordersUpdate = new Orders();
        ordersUpdate.setId(orders.getId());
        ordersUpdate.setStatus(Orders.DELIVERY_IN_PROGRESS);
        ordersUpdate.setDeliveryTime(LocalDateTime.now());
        orderMapper.upDate(ordersUpdate);
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = orderMapper.selectById(ordersConfirmDTO.getId());
        if (orders == null && !Objects.equals(orders.getStatus(), Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders ordersUpdate = new Orders();
        ordersUpdate.setId(orders.getId());
        ordersUpdate.setStatus(Orders.CONFIRMED);
        orderMapper.upDate(ordersUpdate);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = orderMapper.selectById(ordersRejectionDTO.getId());
        if (orders == null && !Objects.equals(orders.getStatus(), Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders ordersUpdate = new Orders();
        ordersUpdate.setId(orders.getId());
        ordersUpdate.setStatus(Orders.CANCELLED);
        ordersUpdate.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        ordersUpdate.setCancelTime(LocalDateTime.now());
        orderMapper.upDate(ordersUpdate);
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code","ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        // 根据订单号查询订单
        paySuccess(ordersPaymentDTO.getOrderNumber());

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);
        ordersDB.setStatus(Orders.TO_BE_CONFIRMED);
        ordersDB.setId(ordersDB.getId());
        ordersDB.setPayStatus(Orders.PAID);
        ordersDB.setCheckoutTime(LocalDateTime.now());
        orderMapper.upDate(ordersDB);

//        下单后往商家端发出来单提醒
        Map map = new HashMap();
        map.put("type",1);
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号"+ordersDB.getNumber());

        String json = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }
}
